package db;

import java.sql.*;

import org.osoa.sca.annotations.Service;
import org.osoa.sca.annotations.Init;
import org.osoa.sca.annotations.Destroy;
import org.osoa.sca.annotations.Property;

@Service(DataAccessService.class)
public class DataAccessServiceImpl implements DataAccessService {
	/**
	 * Default database url, username, password.
	 * Configurable. Maybe use some set property method.
	 */
	@Property
	protected String databaseURL = "jdbc:mysql://localhost:3306/shipping_export";
	
	@Property
	protected String username = "kodylau";
	
	@Property
	protected String pwd = "123";
	
	private Connection connection;
	
	/**
	 * Connect database.
	 */
	@Init
	public void init() {
		try {
			//Register the JDBC driver for MySQL.
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("Connecting to database: " + databaseURL + " ...");
			connection = DriverManager.getConnection(databaseURL, username, pwd);
			System.out.println("Database connection succeed.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Release database connection.
	 */
	@Destroy
	public void shutdown() {
		if (connection != null) {
			try {
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				connection = null;
			}
		}
	}
	
	public ResultSet query(String sql) {
		ResultSet res = null;
		try {
			Statement stmt = connection.createStatement();
			res = stmt.executeQuery(sql);
			System.out.println("Query: " + sql + " done.");
			//return res;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public void update(String sql) {
		try {
			Statement stmt = connection.createStatement();
			stmt.executeUpdate(sql);
			System.out.println("Update: " + sql + " done.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
